//
//  EFHomeViewController.m
//  insurance
//
//  Created by 王长飞 on 2019/9/26.
//  Copyright © 2019年 王长飞. All rights reserved.
//

#import "MallViewController.h"
#import "InformationController.h"
#import "GoodsDetailController.h"
#import "WKWebViewController.h"
#import "MoreGoodsController.h"
#import "HomeBannerModel.h"
#import "HomeNavigationModel.h"
#import "MallRecommendModel.h"
#import "EFAdView.h"
#import "HomeNavButton.h"
#import "KKNoticeView.h"
#import "JumpUtils.h"

@interface MallViewController ()<BaseModelProtocol,UIScrollViewDelegate>
@property (nonatomic,strong)UIView *searchBgView ;

@property (nonatomic,strong)HomeBannerModel *bannerModel ;
@property (nonatomic,strong)HomeNavigationModel *navigationModel ;
@property (nonatomic,strong)MallRecommendModel *recommendModel;

@property (nonatomic,strong)UIView *bannerBgView ;
@property (nonatomic,strong)UIScrollView *navigationScrollView ;
@property (nonatomic,strong)NSArray *navigationArray ;

@property (nonatomic,strong)UIScrollView *recommednScrollView ;
@property (nonatomic,strong)NSArray *categoryList;

@end

@implementation MallViewController


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self navigationDragCanBack:YES];
    
    EFAppContext *appc = [EFAppContext sharedContext];
    if (!ISEMPTY(appc.ACCESS_TOKEN)) {
    }
    //获取banner配置：首页工作台30 8标准电商 25保险产品
    [self.bannerModel getHomeBannerDataWith:@"8"];
    if(self.navigationArray.count == 0) [self.navigationModel getHomeNavigationDataWith:@"8"];
    if(self.categoryList.count == 0)  [self.recommendModel getRecommendData];

}

- (void)getDataFinish:(BaseModel *)baseModel netError:(NSError *)error{
    
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{
    if ([baseModel isKindOfClass:[HomeBannerModel class]])
    {
        HomeBannerResponse *resp = (HomeBannerResponse *)response;
        NSData *jsonData = [resp.resObject.menuJson dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSArray *array = dict[@"bannerList"];
        [self reloadBannerViewWith:array];
    }
    else if ([baseModel isKindOfClass:[HomeNavigationModel class]])
    {
        HomeNavigationResponse *resp = (HomeNavigationResponse *)response;
        NSData *jsonData = [resp.resObject.menuJson dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSArray *array = dict[@"bannerList"];
        self.navigationArray = array;
        [self.navigationScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self setUpNavigationViewWith:array];
    }
    else if ([baseModel isKindOfClass:[MallRecommendModel class]])
    {
        MallRecommendResponse *resp = (MallRecommendResponse *)response;
        NSArray<MallRecommendCategoryList> *categoryList = resp.resObject.categoryList;
        self.categoryList = categoryList;
        [self setUpRecommedView:categoryList];
    }
}

- (void)initView
{
    [super initView];
    
    self.view.backgroundColor = kColorDefultBg;
    [self.view addSubview:self.statusOrangeView];
    [self.view addSubview:self.searchBgView];
    [self.view addSubview:self.bannerBgView];
    [self.view addSubview:self.navigationScrollView];
    [self.view addSubview:self.recommednScrollView];

}

- (void)reloadBannerViewWith:(NSArray *)response
{
    NSMutableArray *urlArray = [NSMutableArray array];
    for(int i = 0; i < response.count; i++){
        NSDictionary *dic = response[i];
        [urlArray addObject:dic[@"bannerPic"]];
    }
    
    [self.bannerBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    EFAdView *adView = [EFAdView adScrollViewWithFrame:CGRectMake(0, 0, self.bannerBgView.width, self.bannerBgView.height) modelArray:urlArray imagePropertyName:@"imgurl" titlePropertyName:@"name"];
    __weak typeof(self) weakSelf = self;
    adView.callBack = ^(NSInteger index,id model){
        
        InformationController *infoVC = [[InformationController alloc]init];
        infoVC.secondMenu = response[index][@"secondMenu"];
        [weakSelf.navigationController pushViewController:infoVC animated:YES];
   
    };
    [self.bannerBgView addSubview:adView];
}

- (void)setUpNavigationViewWith:(NSArray *)array{
    
    CGFloat btnWidth = SCREEN_WIDTH / 4 ;
    CGFloat btnHeight = self.navigationScrollView.height;
    for (int i = 0 ; i < array.count; i++){
        NSDictionary *dic = array[i];
        HomeNavButton *relatedButton = [[HomeNavButton alloc]initWithFrame:CGRectMake(i*btnWidth+10,0, btnWidth, btnHeight)];
        [relatedButton setHimgName:dic[@"bannerPic"]];
        [relatedButton setTitleName:dic[@"secondMenuName"]];
        relatedButton.tag = 100 + i;
        [relatedButton addTarget:self action:@selector(relatedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationScrollView addSubview:relatedButton];
    }

    self.navigationScrollView.contentSize = CGSizeMake((btnWidth+10)*10,0);
}

- (void)relatedButtonClick:(UIButton *)btn{
    
    NSDictionary *dic = self.navigationArray[btn.tag-100];
    NSString *firstMenu = [NSString stringWithFormat:@"%@",dic[@"firstMenu"]];
    NSString *secondMenu = [NSString stringWithFormat:@"%@",dic[@"secondMenu"]];
    NSString *thirdUrl = [NSString stringWithFormat:@"%@",dic[@"thirdMenuUrl"]];
    [JumpUtils jumpToOtherPage:self firstMenu:firstMenu secondMenu:secondMenu thirdUrl:thirdUrl];
}

- (void)setUpRecommedView:(NSArray<MallRecommendCategoryList> *)categoryList
{
    for (int i = 0; i <categoryList.count;i++) {
        MallRecommendCategoryList *category = categoryList[i];
        UIView *infoBgView = [[UIView alloc]initWithFrame:CGRectMake(10, self.recommednScrollView.contentSize.height, self.recommednScrollView.width-20, 10)];
        infoBgView.tag = 100+i;
        [self.recommednScrollView addSubview:infoBgView];
        
        UIView *leftLine = [[UIView alloc]initWithFrame:CGRectMake(0, 6, 4, 14)];
        [leftLine setCornerRedius:1];
        leftLine.backgroundColor = UIColorFromRGB1(0xffcc0000);
        [infoBgView addSubview:leftLine];
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, 200, 20)];
        titleLab.text = category.homepageCategoryName;
        titleLab.textColor = kTitleColor_midden;
        titleLab.font = kFontMidden;
        [infoBgView addSubview:titleLab];
        
        UILabel *moreLab = [[UILabel alloc] initWithFrame:CGRectMake(infoBgView.width-70, 3, 70, 20)];
        moreLab.text = @"更多优品";
        moreLab.tag = 1000+i;
        moreLab.textColor = kTitleColor_light;
        moreLab.font = [UIFont systemFontOfSize:14];
        moreLab.textAlignment = NSTextAlignmentRight;
        [moreLab addTapCallBack:self sel:@selector(moreLabTap:)];
        [infoBgView addSubview:moreLab];
        
        CGFloat btnWidth = infoBgView.width / 2 ;
        CGFloat btnHeight = 190;
        NSArray<MallRecommendProductList> *productList = category.productList;
        for (int k = 0 ; k < productList.count; k++){
            UIView *productView = [[UIView alloc]initWithFrame:CGRectMake((k%2)*btnWidth,(k/2)*(btnHeight+10)+35, btnWidth, btnHeight)];
            productView.tag = 10000+k;
            [productView addTapCallBack:self sel:@selector(productViewTap:)];
            [infoBgView addSubview:productView];
            
            MallRecommendProductList *product = productList[k];
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((productView.width-130)/2,0, 130, 140)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:product.indexPic] placeholderImage:kDefaultImage];
            [productView addSubview:imageView];
            
            UILabel *nameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bottom+10, productView.width, 30)];
            nameLab.text = product.title;
            nameLab.textColor = kTitleColor_black;
            nameLab.font = [UIFont systemFontOfSize:12];
            nameLab.numberOfLines = 2;
            [productView addSubview:nameLab];
            
            UILabel *promotionPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, nameLab.bottom, 300, 20)];
            promotionPriceLab.text = [NSString stringWithFormat:@"¥%@",product.promotionPrice];
            promotionPriceLab.textColor = [UIColor redColor];
            promotionPriceLab.font = kFontMidden;
            [productView addSubview:promotionPriceLab];
            
            float width = [PublicUtils getLabelWidthWithString:promotionPriceLab.text font:promotionPriceLab.font];
            UILabel *originalPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(width+10, promotionPriceLab.top+5, 200, 12)];
            originalPriceLab.font = kFontMimi;
            originalPriceLab.textColor = kTitleColor_light;
            [productView addSubview:originalPriceLab];
            
            NSString *originalPrice = product.originalPrice;
            NSUInteger length = [originalPrice length];
            NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:originalPrice];
            [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, [originalPrice length])];
            [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, length)];
            [originalPriceLab setAttributedText:attri];
        }
        infoBgView.height = ceil((double)productList.count/2) * (btnHeight+10)+40;
        self.recommednScrollView.contentSize = CGSizeMake(0, self.recommednScrollView.contentSize.height+infoBgView.height);
        
    }
}

- (void)moreLabTap:(UIGestureRecognizer *)tap{
    MallRecommendCategoryList *category = self.categoryList[tap.view.tag-1000];
    MoreGoodsController *moreVC = [[MoreGoodsController alloc]init];
    moreVC.categoryId = category.eid;
    [self.navigationController pushViewController:moreVC animated:YES];
}

- (void)productViewTap:(UIGestureRecognizer *)tap{
    MallRecommendCategoryList *category = self.categoryList[tap.view.superview.tag-100];
    NSArray<MallRecommendProductList> *productList = category.productList;
    MallRecommendProductList *product = productList[tap.view.tag-10000];
    //商品详情模式：1默认模式，为空也默认 2三方链接
    if(product.shopProductDetailMode == 2){
        WKWebViewController *webController = [[WKWebViewController alloc]init];
        webController.titleString = @"详情";
        webController.urlString = product.thirdUrl;
        [self.navigationController pushViewController:webController animated:YES];
    }else{
        GoodsDetailController *detailVc = [[GoodsDetailController alloc]init];
        detailVc.productId = product.eid;
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}

- (void)searchClick{
    MoreGoodsController *moreVC = [[MoreGoodsController alloc]init];
    [self.navigationController pushViewController:moreVC animated:YES];
}

- (UIView *)searchBgView{
    if(nil == _searchBgView){
        
        _searchBgView = [[UIView alloc]initWithFrame:CGRectMake(0, self.statusOrangeView.height, SCREEN_WIDTH, 65)];
        _searchBgView.backgroundColor = [UIColor whiteColor];
        [_searchBgView addTapCallBack:self sel:@selector(searchClick)];
        
        UIView *searchFieldBgView = [[UIView alloc]initWithFrame:CGRectMake(15, 25, _searchBgView.width-90, 30)];
        [searchFieldBgView setViewEdgeWithBorderWidth:1 cornerRadius:5 borderColor:kTitleColor_light];
        [_searchBgView addSubview:searchFieldBgView];
        
        UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 16, 16)];
        searchImage.image = [UIImage imageNamed:@"search_icon.png"];
        [searchFieldBgView addSubview:searchImage];
        
        UITextField *searchField =[[UITextField alloc] initWithFrame:CGRectMake(searchImage.right+10, 0, searchFieldBgView.width-searchImage.right-10, searchFieldBgView.height)];
        searchField.font = KFontSmall;
        searchField.placeholder = @"  搜索";
        searchField.userInteractionEnabled = NO;
        [searchFieldBgView addSubview:searchField];
        
        UILabel *searchLab = [[UILabel alloc] initWithFrame:CGRectMake(searchFieldBgView.right+8, 25, 50, 30)];
        searchLab.text = @"搜索";
        searchLab.textColor = kTitleColor_midden;
        searchLab.font = KFontSmall;
        searchLab.backgroundColor = UIColorFromRGB1(0xfffde0bb);
        [searchLab setCornerRedius:5];
        searchLab.textAlignment = NSTextAlignmentCenter;
        [_searchBgView addSubview:searchLab];
    }
    return  _searchBgView;
}


- (UIView *)bannerBgView
{
    if (nil == _bannerBgView) {
        _bannerBgView = [[UIView alloc]initWithFrame:CGRectMake(10, _searchBgView.bottom, SCREEN_WIDTH-20, 160)];
        _bannerBgView.userInteractionEnabled = YES ;
    }
    return _bannerBgView ;
}

- (UIScrollView *)navigationScrollView
{
    if (nil == _navigationScrollView) {
        _navigationScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, self.bannerBgView.bottom+10, SCREEN_WIDTH-20, 96)];
        _navigationScrollView.delegate = self;
        _navigationScrollView.alwaysBounceVertical = YES ;
        _navigationScrollView.showsVerticalScrollIndicator = NO ;
        _navigationScrollView.backgroundColor = kColorDefultCell;
    }
    return _navigationScrollView ;
}

- (HomeBannerModel *)bannerModel{

    if (nil == _bannerModel) {
        _bannerModel = [[HomeBannerModel alloc]initWithDelegate:self cache:NO];
    }
    return _bannerModel;
}

- (HomeNavigationModel *)navigationModel{

    if (nil == _navigationModel) {
        _navigationModel = [[HomeNavigationModel alloc]initWithDelegate:self cache:NO];
    }
    return _navigationModel;
}

- (NSArray *)navigationArray{
    if (nil == _navigationArray) {
        _navigationArray = [NSArray array];
    }
    return _navigationArray;
}

- (MallRecommendModel *)recommendModel{
    
    if (nil == _recommendModel) {
        _recommendModel = [[MallRecommendModel alloc]initWithDelegate:self cache:NO];
    }
    return _recommendModel;
}

- (NSArray *)categoryList{
    if (nil == _categoryList) {
        _categoryList = [NSArray array];
    }
    return _categoryList;
}

- (UIScrollView *)recommednScrollView{
    if(nil == _recommednScrollView){
        _recommednScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, self.navigationScrollView.bottom+10, SCREEN_WIDTH-20, SCREEN_HEIGHT-KTarBarFullHeight-self.navigationScrollView.bottom-10)];
        _recommednScrollView.showsVerticalScrollIndicator = NO;
        [_recommednScrollView setCornerRedius:5];
        _recommednScrollView.backgroundColor = [UIColor whiteColor];
        _recommednScrollView.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
    }
    return _recommednScrollView;
}
@end
